dojo.provide('jetty.Server');

dojo.require('rhino.lang.java');
dojo.require('jetty.httpservlet');

ph.require('org.mortbay.jetty.Server');
ph.require('org.mortbay.jetty.Connector');
ph.require('org.mortbay.jetty.bio.SocketConnector');
ph.require('org.mortbay.jetty.servlet.Context');
ph.require('org.mortbay.jetty.servlet.DefaultServlet');
ph.require('org.mortbay.jetty.servlet.ServletMapping');
ph.require('org.mortbay.jetty.servlet.ServletHandler');
ph.require('org.mortbay.jetty.servlet.ServletHolder');
ph.require('org.mortbay.jetty.handler.ContextHandler');
ph.require('org.mortbay.resource.FileResource');

dojo.declare('jetty.Server', null, {
  constructor: function(port, resources) {
    var connector = new org.mortbay.jetty.bio.SocketConnector;
    connector.setPort(port);
    
    this._server = new org.mortbay.jetty.Server;
    this._server.setConnectors(rhino.lang.java.toArray(org.mortbay.jetty.Connector, [connector]));
    
    if (resources) {
      for (base in resources) {
        if (!resources.hasOwnProperty(base))
          continue;
        
        this.registerResource(resources[base], base);
      }
    }
  },
  
  registerResource: function(path, base) {
    org.mortbay.resource.FileResource.setCheckAliases(false);
    var context = new org.mortbay.jetty.servlet.Context(this._server, path, org.mortbay.jetty.servlet.Context.SESSIONS);
    context.setResourceBase(base);
    context.addServlet(org.mortbay.jetty.servlet.DefaultServlet, '/');
  },
  
  register: function(path, callbacks) {
    if (typeof callbacks == 'function') callbacks = { get: callbacks };
    
    var descriptor = jetty.httpservlet.createDescriptor(callbacks);
    
    var mapping = new org.mortbay.jetty.servlet.ServletMapping;
    mapping.setPathSpec('/');
    mapping.setServletName(descriptor.name);
    
    var handler = new org.mortbay.jetty.servlet.ServletHandler;
    handler.setServlets(rhino.lang.java.toArray(org.mortbay.jetty.servlet.ServletHolder, [descriptor.holder]));
    handler.setServletMappings(rhino.lang.java.toArray(org.mortbay.jetty.servlet.ServletMapping, [mapping]));
    
    var context = new org.mortbay.jetty.handler.ContextHandler;
    context.setContextPath(path);
    context.setClassLoader(descriptor.classloader);
    context.setHandler(handler);
    this._server.addHandler(context);
  },
  
  start: function() {
    this._server.start();
  },
});